package cms.simmytech.dialect;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;

public class MomentImgDialect extends AbstractElementTagProcessor {

	Log log = LogFactory.getLog(RoleCustomDialect.class);

	private static final String TAG_NAME = "img";
	private static final int PRECEDENCE = 1000;
	private String webPath;

	public MomentImgDialect(final String dialectPrefix,final String webPath) {
		super(TemplateMode.HTML, // 此处理器将仅应用于HTML模式
				dialectPrefix, // 要应用于名称的匹配前缀
				TAG_NAME, // 标签名称：匹配此名称的特定标签
				true, // 没有应用于标签名的前缀
				null, // 无属性名称：将通过标签名称匹配
				false, // 没有要应用于属性名称的前缀
				PRECEDENCE// 优先(内部方言自己的优先
		);
		this.webPath=webPath;
	}

	@Override
	protected void doProcess(ITemplateContext context, IProcessableElementTag tag,
			IElementTagStructureHandler structureHandler) {
		
		String src = tag.getAttributeValue("src");
		if (!StringUtils.isEmpty(src)) {
			src=getExpressionValue(context, src).toString();
			String[] paths=src.split("\\|\\|");
			StringBuffer sBuffer=new StringBuffer();
			for(String path:paths) {
				if(StringUtils.isEmpty(path)) {
					continue;
				}
				sBuffer.append("<img src='");
				sBuffer.append(webPath);
				sBuffer.append(path);
				sBuffer.append("' style='width:100px;height:100px;margin-left:20px;'/>");
				
			}
			IModelFactory modelFactory = context.getModelFactory();
			IModel model = modelFactory.createModel();
			model.add(modelFactory.createText(sBuffer.toString()));
			structureHandler.replaceWith(model, false);

		}
	}
	private Object getExpressionValue(ITemplateContext iTemplateContext, String expressionString) {
	    final IEngineConfiguration configuration = iTemplateContext.getConfiguration();
	    final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
	    // 解析expression
	    final IStandardExpression expression = parser.parseExpression(iTemplateContext, expressionString);
	    // 获取expression的执行结果
	    Object obj =expression.execute(iTemplateContext);
	    if(obj==null) {
	    	return "";
	    }
	    return obj;
	}

}
